package com.apes.fn.scm.retailOrder.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.ApesBean;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.JpaUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import com.apes.scm.masterdata.stock.model.Location;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 功能：零售单明细
 *
 * @author HuJinalin
 * @create 2018-10-31 15:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailOrderItem.CONST_TABLE_NAME, indexes = {@Index(columnList = "source")})
public class RetailOrderItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "retail_order_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "销售订单明细")
    private String id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "sale_id", referencedColumnName = "id", nullable = false)
    private RetailOrder order;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company; //公司


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("库存位置")
    private Location location;  //库存位置

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier; //供应商  //2021-04-09 如果是app传入的年审订单，供应商直接上

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "origin_supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole originSupplier; // 原始供应商（由于正向写入凭证的时候，会变更供应商字段值，导致退货时找不到供应商字段）

    @Column(name = "remark", length = 400)
    @Comment("备注")
    private String remark;

    @Column(name = "uom_name", length = 120)
    @Comment("计量单位名称")
    private String uomName;

    @Column(name = "originnumber", length = 120)
    @Comment("来源明细编号")
    private String originnumber;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "platform_id", referencedColumnName = "id")
    @Comment("平台")
    private PartyRole platform;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id", nullable = false)
    @Comment("商品")
    private Product product;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("小计（未含税金额）")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    public void setPriceUnit(double priceUnit) {
        if (priceUnit < 0) throw new RuntimeException("单价不能传负数，请检查!");
        this.priceUnit = priceUnit;
    }

    @Column(name = "price_limit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("限价")
    private double priceLimit = 0;

    @Column(name = "product_uom_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("数量")
    private double productUomQty = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id", nullable = false)
    @Comment("税率")
    private Tax tax;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_voucher", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("凭证数量")
    private double qtyVoucher = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("交货数量")
    private double qtyDeliver = 0;

    @Column(name = "qty_cancle", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("取消数量")
    private double qtyCancle = 0;

    @Column(name = "qty_returned", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已退货数量")
    private double qtyReturned = 0;

    @Column(name = "qty_returning", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货中...")
    private double qtyReturning = 0;

    @Column(name = "qty_delivering", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("提单冲红数量")
    private double qtyDelivering = 0;

    @Column(name = "qty_delivered", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货冲红数量")
    private double qtyDelivered = 0;

    @Column(name = "oos", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("无库存销售标记")
    private boolean oos = false; //无库存销售标记（OOS：out of stock）

    @Comment("主销售员")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "main_Salesman", referencedColumnName = "id")
    private PartyRole mainSalesman;

    @Comment("辅销售员")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "sub_Salesman", referencedColumnName = "id")
    private PartyRole subSalesman;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "barch_code", referencedColumnName = "id")
    @Comment("商品批次内码")
    private InventoryBatch inventoryBatch; // 指定商品批次（带安/服务）

    @Comment("带安标记")
    @Column(name = "product_rule", nullable = false, columnDefinition = "number(1,0) default 0")
    private int productRule;//0  有库存商品  10  带安商品（代销）  20  带安商品（经销）  30  其他商品

    @Column(name = "price_out_unit_in_tax", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("含税带安成本单价")
    private double priceOutUnitInTax = 0;  //2021-04-09 如果是app传入的年审订单，成本放这里;

    @Column(name = "discount_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("折扣金额")
    private double discountAmount = 0;


    @Column(name = "balance_consumption", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("余额消费")
    private double balanceConsumption = 0;


    @Column(name = "inner_sale_price_unit", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("内部销售单价")
    private double innerSalePriceUnit = 0;      // 外协代销带安找供应商采购价(非跨公司)

    @Column(name = "source", length = 30)
    @Comment("来源单据明细号")
    private String source;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("外协采购合同")
    private Contract contract;


    @Column(name = "lock_price",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("锁价")
    private double lockPrice = 0;

    @Column(name = "original_sales_unit_price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("原销售单价")
    private double originalSalesUnitPrice = 0;

    @Column(name = "pft_price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("原优惠单价")
    private double pftPriceUnit = 0;    // 服务方案上销售单价

    @Column(name = "assessment_cost_price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("考核成本价")
    private double assessmentCostPrice = 0;

    /***
     * 类型为订金或者年卡
     */
    @Column(name = "platform_management_fee", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("平台管理费")
    private double platformManagementFee = 0;

    @Column(name = "refer_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("参考成本")
    private double referTax = 0;

    @Column(name = "supply_Chain_Management", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("供应链管理费用")
    private double supplyChainManagement = 0;

    @Column(name = "estimated_commission", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预估提成")
    private double estimatedCommission = 0;

    @Column(name = "invoiced_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("已开票金额")
    private double invoicedAmount = 0;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;

    @Column(name = "pack_id", length = 128)
    @Comment("套包编码")
    private String packId;

    @Transient
    private PartyRole owner; //物权公司

    public PartyRole getOwner() {
        if (location != null) return location.getCompany();
        return company;
    }

    public void checkProductDiscountAmount(){
        if (this.discountAmount == 0) return;
        double discountAmount = this.retailDiscounts.stream().mapToDouble(RetailOrderDiscount::getDiscountAmount).sum();
        // 折扣总金额不能超过商品销售金额
        if (Math.abs(this.priceTotal) < Math.abs(Arith.round(discountAmount, 2))) {
            throw new RuntimeException("折扣总金额不能超过商品销售金额，商品编码：" + this.product.getId() + "，销售金额：" + this.getPriceTotal() + "，折扣总金额：" + discountAmount);
        }
    }

    public double getDiscountAmount() {
        double discountAmount = 0;
        for (RetailOrderDiscount orderDiscount : retailDiscounts) {
            discountAmount +=  orderDiscount.getDiscountAmount();
        }
        return discountAmount;
    }

    @OneToMany(mappedBy = "retailOrderItem", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<RetailOrderDiscount> retailDiscounts = new HashSet(); //折扣明细行

    public Set<RetailOrderDiscount> getRetailDiscounts() {
        double discountAmounts = 0;
        double balanceConsumptions = 0;
        for (RetailOrderDiscount orderDiscount : retailDiscounts) {
            orderDiscount.setRetailOrder(order);
            orderDiscount.setRetailOrderItem(this);
            //获取折扣总金额
            discountAmounts += orderDiscount.getDiscountAmount();
            if("年卡销售".equals(orderDiscount.getCouponResource())){
                balanceConsumptions+=orderDiscount.getCouponDiscountAmount();
            }
        }
        if(balanceConsumptions!=0||discountAmounts!=0){
            balanceConsumption=balanceConsumptions;
            discountAmount = discountAmounts;
        }
        return retailDiscounts;
    }


    public void setRetailDiscounts(Set<RetailOrderDiscount> retailDiscounts) {
        if (retailDiscounts == null) retailDiscounts = new HashSet<>();
        this.retailDiscounts.clear();
        this.retailDiscounts.addAll(retailDiscounts);
    }


    public void setSubSalesman(PartyRole subSalesman) {
        if (subSalesman!=null&&StringUtil.isEmpty(subSalesman.getId())) {
            this.subSalesman = null;
        } else {
            this.subSalesman = subSalesman;
        }
    }

    public void setMainSalesman(PartyRole mainSalesman) {
        if (Objects.isNull(mainSalesman) || StringUtil.isEmpty(mainSalesman.getId())) {
            this.mainSalesman = null;
        } else {
            this.mainSalesman = mainSalesman;
        }
    }

    @Column(name = "paint_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("油漆价格")
    private Double paintPrice; // 油漆价格

    @Column(name = "paint_purchase_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("油漆采购价格")
    private Double paintPurchasePrice; // 油漆采购价格

    @Column(name = "paint_Flag", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE) // nullable = false,
    @Comment("油漆商品标记")
    private boolean paintFlag = false; // 油漆商品标记

    @Column(name = "paint_type", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("油漆类别(0:水性;1:油性)")
    private int paintType = 0;  // 油漆类别(0:水性;1:油性)

    @Transient
    private Double marketableQty;  // 获取实时库存

    public Double getMarketableQty() {
        if (!order.getState().equals("sent")) return null;
        ProductAccountService productAccountService = SpringManager.getBean(ProductAccountService.class);
        Map map = productAccountService.getUsableQtyToUom(location, product, uom, company);
        if (map.isEmpty()) return 0.00;
        return (Double) map.get("marketableQty") + productUomQty;
    }

    @Transient
    private double qtyDeliveringLimit; //可提单冲红数量

    public double getQtyDeliveringLimit() {
        if (productRule == 0) {
            return productUomQty - qtyDeliver - qtyCancle - qtyDelivering;
        } else if (productRule == 10 || productRule == 20) {
            if (LogicalUtil.in(product.getType(), "aut")) {
                return productUomQty - qtyDelivering - qtyCancle;
            } else {
                return -qtyCancle - qtyDelivering;
            }
        } else {
            return productUomQty - qtyDelivering - qtyCancle;
        }
    }

    @Transient
    private double qtyDeliveredLimit; //可退货冲红数量

    public double getQtyDeliveredLimit(){
        if (productRule == 0) {
            return qtyDeliver - (qtyReturned - qtyCancle) - qtyDelivered;
        } else if (productRule == 10 || productRule == 20) {
            if (LogicalUtil.in(product.getType(), "aut")) {
                return 0;
            } else {
                return productUomQty - (qtyReturned - qtyCancle) - qtyDelivered;
            }
        } else {
            return 0;
        }
    }

    /**
     * 计算金额
     */
    public void computeAmt() {
        Map result = this.computeTax().computeAll(this.getCompany(), priceUnit, productUomQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
    }

    private Tax computeTax() {
        TaxService taxService = SpringManager.getBean(TaxService.class);
        tax = taxService.getSaleTax(order.getCompany(), product);
        return tax;
    }

    /**
     * 功能：计算无税库存单价
     *
     * @return
     */
    public double computeExcludedPriceUnit() {
        double price = this.priceUnit;
        if (this.getTax() != null) {
            price = (double) this.getTax().computeAll(this.getOrder().getCompany(), price, 1.0).get("totalExcluded");
        }
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算含税库存单价
     *
     * @return
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算基本单位库存量
     *
     * @param uomQty
     * @return
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.getCompany(), this.getProduct());
    }

    /**
     * 交货
     *
     * @param qtyDone
     */
    public void delivery(double qtyDone) {
        this.qtyDeliver += qtyDone;
        // 当前可交货数量 = 销售数量 - 取消数量
        if (qtyDeliver > productUomQty - qtyCancle) {
            throw new RuntimeException("交货和取消数量之和不能大于销售数量，当前可交货数量：" + (productUomQty - qtyCancle));
        }
    }

    /**
     * 取消
     *
     * @param qtyDone
     */
    public void cancle(double qtyDone) {
        this.qtyCancle += qtyDone;
        // 当前可取消数量 = 销售数量 - 交货数量
        if (qtyCancle > productUomQty - qtyDeliver) {
            throw new RuntimeException("交货和取消数量之和不能大于销售数量，当前可退数量：" + (productUomQty - qtyDeliver));
        }
    }

    /**
     * 合计退货中数量
     *
     * @param qtyDelivering 提单冲红数量
     * @param qtyDelivered  退货冲红数量
     */
    public void sumQtyReturning(double qtyDelivering, double qtyDelivered) {
        this.qtyDelivering += qtyDelivering;
        this.qtyDelivered += qtyDelivered;
        this.qtyReturning = this.qtyDelivering + this.qtyDelivered;
        if ((productUomQty - qtyReturned) < qtyReturning)
            throw new RuntimeException("退货数量不能大于销售数量，当前可退货数量为：" + (productUomQty - qtyReturned));
    }

    /**
     * 退货在途 +  已退货 <= 销售数量
     *
     * @param qtyReturned 已退货数量
     */
    public void calcQtyReturned(double qtyReturned) {
        if ((this.qtyReturned + qtyReturned + this.qtyReturning) > productUomQty)
            throw new RuntimeException("退货在途数量和已退货数量之和不能大于可退货数量，当前可退数量：" + (productUomQty - this.qtyReturned - this.qtyReturning));
        this.qtyReturned += qtyReturned;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != JpaUtil.getDomainClass((ApesBean) o)) return false;
        RetailOrderItem item = (RetailOrderItem) o;
        return Objects.equals(id, item.getId());
    }
}
